package com.jgads.ad.sdk.mediation.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.banner.MediationCustomBannerLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.jgads.ad.sdk.mediation.utils.ThreadUtils;
import com.junion.ad.BannerAd;
import com.junion.ad.bean.BannerAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.BannerAdListener;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 12/23/21 6:05 PM
 */
public class CustomerBannerAdapter extends MediationCustomBannerLoader {

    private FrameLayout flContainer;
    private BannerAd bannerAd;

    @Override
    public void load(final Context context, AdSlot gmAdSlotBanner, final MediationCustomServiceConfig gmCustomServiceConfig) {
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                flContainer = new FrameLayout(context);
                flContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                bannerAd = new BannerAd(context, flContainer);
                bannerAd.setListener(new BannerAdListener() {
                    @Override
                    public void onAdExpose(BannerAdInfo adInfo) {
                        callBannerAdShow();
                    }

                    @Override
                    public void onAdClick(BannerAdInfo adInfo) {
                        callBannerAdClick();
                    }

                    @Override
                    public void onAdClose(BannerAdInfo adInfo) {
                        callBannerAdClosed();
                    }

                    @Override
                    public void onAdReceive(BannerAdInfo adInfo) {
                        callLoadSuccess();
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        callLoadFail(error.getCode(), error.getError());
                    }
                });
                if (gmCustomServiceConfig != null) {
                    bannerAd.loadAd(gmCustomServiceConfig.getADNNetworkSlotId());
                }
            }
        });
    }

    @Override
    public View getAdView() {
        return flContainer;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bannerAd != null) {
            bannerAd.release();
            bannerAd = null;
        }
        flContainer = null;
    }
}
